package cn.huaqingcheng.tool.http;

import cn.huaqingcheng.tool.core.DelayedInit;
import cn.huaqingcheng.tool.http.spi.HttpClient;
import cn.huaqingcheng.tool.http.spi.HttpClientProvide;
import cn.huaqingcheng.tool.json.JsonProvide;

import java.io.File;
import java.nio.file.Path;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.function.Supplier;

/**
 * HttpTool
 **/
@SuppressWarnings({"unused", "ClassNamePrefixedWithPackageName"})
public interface HttpTool {

    Supplier<HttpClient> CLIENT = new DelayedInit<>(() -> ServiceLoader.load(JsonProvide.class.getModule().getLayer(), HttpClientProvide.class)
        .stream()
        .map(ServiceLoader.Provider::get)
        .sorted()
        .findFirst()
        .map(HttpClientProvide::getClient)
        .orElseThrow(() -> new ServiceConfigurationError("SPI 错误: 找不到 %s 实现".formatted(HttpClientProvide.class.getName())))
    );

    static String exec(HttpRequest request) {
        try {
            HttpResponse<String> response = CLIENT.get().exec(request);
            return response.body();
        } catch (Exception e) {
            throw new HttpStatusException(e);
        }
    }

    static Object download(HttpRequest request, File file) {
        try {
            HttpResponse<Path> exec = CLIENT.get().exec(request, file);
            return exec.body();
        } catch (Exception e) {
            throw new HttpStatusException(e);
        }
    }

}
